<?php
/**
 * Created by PhpStorm.
 * User: 余智勇
 * Date: 2018/11/28
 * Time: 18:40
 */

namespace app\storage\model;


use app\admin\controller\StorageController;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;

class UserModel extends Model
{
    protected $table = 'cmf_user';
    protected $pk = 'id';

    public function RoleUser()
    {
        return $this->hasOne('RoleUserModel', 'user_id', 'id')->bind(['role_id', 'parent_id', 'role_name']);
    }

    public function Role()
    {
        return $this->belongsToMany('RoleModel', 'role_user', 'user_id', 'id');
    }

    public function StaffStorage()
    {
        return $this->hasMany('StaffStorageModel', 'user_id', 'id');
    }


    public function addUser($param)
    {
        $this->startTrans();
        $userStorage = $param['storage'];
        $roleUser = ['role_id' => $param['role_id']];
        $param['user_pass'] = cmf_password($param['user_pass']);
        $this->setAttr('RoleUser', $roleUser);
        $result1 = $this->together('RoleUser')->allowField(true)->save($param);
        $result2 = $this->StaffStorage()->saveAll($userStorage);
        if ($result1 && $result2) {
            $this->commit();
            return true;
        } else {
            $this->rollback();
            return true;
        }
    }

    public function editUser($param)
    {
         $userId = $param['userId'];
        $userStorage = $param['storage'];

        $storageList = Db::table('iwh_staff_storage')->where(['user_id' => $userId])->column('storage_uuid');
        $diffStorage1 = array_diff($storageList, $userStorage);
        $diffStorage2 = array_diff($userStorage, $storageList);

        $userPass = Db::table('cmf_user')->where(['id' => $userId])->value('user_pass');
        if ($param['user_pass'] != $userPass) {
            $param['user_pass'] = cmf_password($param['user_pass']);
        }
        $staffStorage = [];
        foreach ($diffStorage2 as $item) {
            $staffStorage[] = [
                'user_id' => $userId,
                'storage_uuid' => $item,
                'is_current' => 0,
                'status' => 1,
                'time' => get_current_time()
            ];
        }
        Db::startTrans();
        $result1 = $result2 = $result3 = $result4 = true;
        if (!empty($diffStorage1)) {
            $result1 = Db::table('iwh_staff_storage')->where(['user_id' => $userId])->whereIn('storage_uuid', $diffStorage1)->update(['status' => 0]);
        }
        if (!empty($diffStorage2)) {
            Db::table('iwh_staff_storage')->where(['user_id' => $userId])->whereIn('storage_uuid', $diffStorage2)->delete();
            $result2 = Db::table('iwh_staff_storage')->insertAll($staffStorage);
        }
        $result3 = Db::table('cmf_user')->strict(false)->where('id', $userId)->update($param);
        $result4 = Db::table('cmf_role_user')->strict(false)->where('user_id', $userId)->update($param);
        if ($result1 && $result2 !== false && $result3 !== false && $result4 !== false) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return true;
        }
    }

    public function deleteUser($id)
    {
        $userId = $id;
        Db::startTrans();
        $result1 = Db::table('iwh_staff_storage')->where(['user_id' => $userId])->delete();
        $result2 = Db::table('cmf_user')->where('id', $userId)->delete();
        $result3 = Db::table('cmf_role_user')->where('user_id', $userId)->delete();
        if ($result1 !== false && $result2 !== false && $result3 !== false) {
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return false;
        }
    }

    public function getCurrentStaffStorage($id = '')
    {
        $userId = empty($id) ? session('ADMIN_ID') : $id;
        if ($userId == 1) {
            $storageModel = new StorageModel();
            $storageList = $storageModel->column('uuid');
        } else {
            $staffStorageModel = new StaffStorageModel();
            $storageList = $staffStorageModel->where('user_id', $userId)->column('storage_uuid');
        }

        $storageList = array_unique($storageList);
        return $storageList;
    }
}